package com.ebt.m.customer.ui;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.listview.ISectionFactory;
import com.ebt.m.commons.buscomponent.listview.IView;
import com.ebt.m.commons.buscomponent.listview.pulltorefresh.PullToRefreshView;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.event.EventCustomerFloatingButtonAction;
import com.ebt.m.customer.fragment.BaseLazySwipeRefreshFragment;
import com.ebt.m.customer.net.json.CustomerDynamicJson;
import com.ebt.m.customer.net.json.CustomerDynamicListJson;
import com.ebt.m.customer.util.CompareHelper;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.event.LoginEvent;
import com.ebt.m.homepage.CustomerEvent;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.view.timeline.InteractionViewCustomerCreate;
import com.ebt.m.view.timeline.InteractionViewInsuranceCreate;
import com.ebt.m.view.timeline.InteractionViewInsuranceEdit;
import com.ebt.m.view.timeline.InteractionViewNoteCreate;
import com.ebt.m.view.timeline.InteractionViewNoteEdit;
import com.ebt.m.view.timeline.InteractionViewPhoneCall;
import com.ebt.m.view.timeline.InteractionViewProposalRead;
import com.ebt.m.view.timeline.InteractionViewProposalSend;
import com.ebt.m.view.timeline.TimeLineRecyclerAdapter2;
import com.ebt.m.widget.EBTProgress;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 客户详情-动态
 */
public class FragmentCustomerInteraction extends BaseLazySwipeRefreshFragment {

    private static final List<Integer> firstLevelEvent = new ArrayList<>();
    private static final List<Integer> secLevelEvent = new ArrayList<>();
    private static final List<Integer> thirdLevelEvent = new ArrayList<>();

    private LinearLayoutManager mLinearLayoutManager;
    private Bundle mGetBundle;
    private TimeLineRecyclerAdapter2 mLineRecycleAdapter;
    private Gson mGson;
    private String customerUuid;

    @BindView(R.id.content_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.iv_empty)
    ImageView mEmptyImageView;
    @BindView(R.id.tv_empty)
    TextView mEmptyTextView;
    @BindView(R.id.btn_empty)
    Button mEmptyButton;
    @BindView(R.id.empty_container)
    LinearLayout mEmptyView;
    @BindView(R.id.load_refresh_net)
    TextView loadRefreshNet;
    @BindView(R.id.load_refresh)
    TextView loadRefresh;
    @BindView(R.id.progress)
    EBTProgress progress;
    Unbinder unbinder;
    private View noNetContainer;
    private View netSlowContainer;

    private ISectionFactory mViewFactory = new ISectionFactory() {
        @Override
        public IView createView(int viewType) {
            IView view = null;
            switch (viewType) {
                case CustomerConstant.InteractionType.CUSTOMER_CREATE:
                    view = new InteractionViewCustomerCreate(getContext());
                    break;
                case CustomerConstant.InteractionType.INSURANCE_CREATE:
                    view = new InteractionViewInsuranceCreate(getContext());
                    break;
                case CustomerConstant.InteractionType.INSURANCE_EDIT:
                    view = new InteractionViewInsuranceEdit(getContext());
                    break;
                case CustomerConstant.InteractionType.PROPOSAL_SEND:
                    view = new InteractionViewProposalSend(getContext());
                    break;
                case CustomerConstant.InteractionType.PROPOSAL_READ:
                    view = new InteractionViewProposalRead(getContext());
                    break;
                case CustomerConstant.InteractionType.NOTE_CREATE:
                    view = new InteractionViewNoteCreate(getContext());
                    break;
                case CustomerConstant.InteractionType.NOTE_EDIT:
                    view = new InteractionViewNoteEdit(getContext());
                    break;
                case CustomerConstant.InteractionType.PHONE_CALL:
                    view = new InteractionViewPhoneCall(getContext());
                    break;
            }
            return view;
        }
    };

    static {
        firstLevelEvent.add(1);
        firstLevelEvent.add(2);
        firstLevelEvent.add(3);
        firstLevelEvent.add(9);
        secLevelEvent.add(4);
        secLevelEvent.add(5);
        thirdLevelEvent.add(6);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_customer_interaction2;
    }

    @Override
    protected void onSwipeRefresh(PullToRefreshView swipeRefreshLayout) {
        initData();
    }

    @Override
    protected void onCreateContentView(View contentView, Bundle savedInstanceState) {
        unbinder = ButterKnife.bind(this, contentView);
        noNetContainer = contentView.findViewById(R.id.no_net_container);
        netSlowContainer = contentView.findViewById(R.id.net_slow_container);
        mLinearLayoutManager = new LinearLayoutManager(getContext().getApplicationContext());
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mLineRecycleAdapter = new TimeLineRecyclerAdapter2(getContext().getApplicationContext(), new ArrayList<>(), mViewFactory);
        mLineRecycleAdapter.setEmptyView(contentView.findViewById(R.id.empty_view));
        mRecyclerView.setAdapter(mLineRecycleAdapter);
        setRecyclerViewTarget(mRecyclerView);
    }

    /**
     * 空图和错误图片显示逻辑
     *
     * @param no_net
     * @param net_slow
     */
    public void showEmpty(boolean empty, boolean no_net, boolean net_slow) {
        if (empty) {
            mEmptyView.setVisibility(View.VISIBLE);
            mEmptyTextView.setText("暂无动态哦");
            mEmptyImageView.setImageResource(R.drawable.ic_empty_interaction);
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mEmptyView.setVisibility(View.GONE);
        }
        noNetContainer.setVisibility(no_net ? View.VISIBLE : View.GONE);
        netSlowContainer.setVisibility(net_slow ? View.VISIBLE : View.GONE);
    }

    private void showProgress() {
        if (progress != null) {
            progress.setVisibility(View.VISIBLE);
        }
    }

    private void hideProgress() {
        if (progress != null) {
            progress.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGson = new Gson();
        initArgs();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onFirstUserVisible() {
        super.onFirstUserVisible();
        getView().postDelayed(new Runnable() {
            @Override
            public void run() {
                showProgress();
                initData();
            }
        }, CustomerConstant.Delay.FRAGMENT_UPDATE_DELAY);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public static FragmentCustomerInteraction newInstance(String uuid) {
        Bundle bundle = new Bundle();
        bundle.putString(CustomerConstant.CUSTOMER_UUID, uuid);
        FragmentCustomerInteraction fragmentCustomerInteraction = new FragmentCustomerInteraction();
        fragmentCustomerInteraction.setArguments(bundle);
        return fragmentCustomerInteraction;
    }

    private void initArgs() {
        mGetBundle = getArguments();
        if (mGetBundle != null) {
            customerUuid = mGetBundle.getString(CustomerConstant.CUSTOMER_UUID);
        }
    }

    private void initData() {
        if (TextUtils.isEmpty(customerUuid)) {
            ToastUtil.showToast("客户ID为空");
            return;
        }
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.getCustomerDynamicList(customerUuid).compose(RxUtil.rxTransformer(this)).subscribe(getInteractionSubscriber());
    }

    private Observer<CustomerDynamicListJson> getInteractionSubscriber() {

        return new Observer<CustomerDynamicListJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                UIHelper.makeToast(getContext(), getString(R.string.network_fail));
                if (NetUtils.isNetworkAvailable(getContext())) {
                    showEmpty(false, false, true);
                } else {
                    showEmpty(false, true, false);
                }

                hideRefresh();
                hideProgress();
            }

            @Override
            public void onNext(CustomerDynamicListJson customerDynamicListJson) {
                if (customerDynamicListJson == null || customerDynamicListJson.error != null || customerDynamicListJson.data == null) {
                    showEmpty(false, false, true);
                } else {
                    convertDynamicListJson(customerDynamicListJson);
                    showDynamic(customerDynamicListJson);
                }
                hideRefresh();
                hideProgress();
            }
        };
    }

    private void convertDynamicListJson(CustomerDynamicListJson customerDynamicListJson) {

        if (customerDynamicListJson != null && customerDynamicListJson.data != null) {
            for (CustomerDynamicJson item : customerDynamicListJson.data) {
                if (!TextUtils.isEmpty(item.activeJson)) {
                    item.objectFromActiveJson = mGson.fromJson(item.activeJson, CustomerDynamicJson.CustomerActiveJson.class);
                }
            }
        }
    }

    private void showDynamic(CustomerDynamicListJson json) {
        List<CustomerDynamicJson> list = json.data;
        Collections.sort(list, CompareHelper.COMPARATOR_CUSTOMER_DYNAMIC_JSON);
        mLineRecycleAdapter.setData(list);
        showEmpty(mLineRecycleAdapter.getItemCount() <= 0, false, false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CustomerEvent event) {
        if (mLineRecycleAdapter != null) {
            initData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginEvent event) {
        if (mLineRecycleAdapter != null) {
            initData();
        }
    }

    @OnClick({R.id.load_refresh_net, R.id.load_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_empty:
                EventBus.getDefault().post(new EventCustomerFloatingButtonAction(EventCustomerFloatingButtonAction.Note));
                break;
            case R.id.load_refresh_net:
                initData();
            case R.id.load_refresh:
                initData();
                break;
        }
    }
}